package com.zh.filetransport.contrl

import com.zh.filetransport.chat.ChatService
import com.zh.filetransport.chat.GetChatService
import com.zh.filetransport.core.FileServer
import com.zh.filetransport.core.GetFileSender
import com.zh.filetransport.model.Mode
import com.zh.util.validateAndExtract
import org.tinylog.Logger;
import org.tinylog.TaggedLogger
import java.io.BufferedReader
import java.io.InputStreamReader

private val log = Logger.tag("StdInputKt")

//从标准输入交互
fun StdInput(mode: String, server: FileServer?, chatService: ChatService?) {
    log.debug("StdInput ...", "")

    if (Mode.Console.name.equals(mode, ignoreCase = true)) {
        println("请输入命令: (提示[exit]退出 [help]帮助) ")
    }

    val reader = BufferedReader(InputStreamReader(System.`in`))
    while (true) {
        val message = reader.readLine()?.trim() ?: continue
        if (message.isEmpty()) continue

        if (message == "exit") {
            server?.shutdown()
            chatService?.shutdown()
            break
        }

        if (message == "help") {
            println("====查看帮助命令如下====")
            println("\t'exit' 退出程序 ")
            println("\t'help' 查看帮助命令 ")
            println("\t'[open] <host>' host是指你要连接的远端IP. 示例'[open] 127.0.0.1' ")
            println("\t'[chat] <message>' message是指你要发送的消息文本. 示例'[chat] hello world ' 或 '[chat-127.0.0.1] hello world '")
            println("\t'[add] <filepath>' filepath是指你要发送的文件或目录的绝对路径. 示例'[add] D:/tmp/hello.txt' ")
            continue
        }

        val (valid, commandText, content) = validateAndExtract(message)
        if (valid) {
//            logrus.info("Call command $commandText")

            val parts = commandText.split("-", limit = 2)
            val command = parts[0]
            val id = if (parts.size > 1) parts[1] else ""

            when (command) {
                "open" -> {
                    val r = CommandOpen(content.trim())
                    println("[${command}] {\"id\": \"${id}\",\"data\": ${r}}")
                }

                "add" -> {
                    CommandAdd(content.trim(), id)
                }

                "chat" -> {
                    val peerIp = id
                    CommandChat(content.trim(), peerIp)
                }

                else -> {
                    log.error("不支持的 command $command", "")
                }
            }
        }
    }

    log.debug("StdInput stop ...", "")
}

fun CommandOpen(peerIp: String): Boolean {
    return GetFileSender().open(peerIp)
}

fun CommandAdd(filepath: String, id: String): Boolean {
    GetFileSender().addToTask(filepath, id)
    return true
}

fun CommandChat(content: String, peerIp: String): Boolean {
    return GetChatService().chatSend(content, peerIp.ifEmpty { GetFileSender().remoteHost() })
}
